package com.cloud.pole.tool.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.springframework.stereotype.Service;

import com.ace.cache.annotation.Cache;
import com.cloud.pole.tool.service.ExpressService;

@Service
public class ExpressServiceImpl implements ExpressService {
	
	private final String host = "https://wuliu.market.alicloudapi.com";       //请求地址  支持http 和 https 及 WEBSOCKET
	private final String appcode = "c2fd7253f41e4c03b5a40861a784a902";
	
	/*
	 * 全国快递物流查询
	 */
	@Cache(key = "kdi{1}", expire = 30)
	@Override
	public String kdi(String no, String type) throws Exception {
		String path = "/kdi";                                     //后缀
        String urlSend = host + path + "?no=" + no + "&type=" + type;   //拼接请求链接
        return httpSend(urlSend);
	}
	
	/*
    读取返回结果
	 */
	private String httpSend(String urlSend) throws IOException {
		URL url = new URL(urlSend);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestProperty("Authorization", "APPCODE " + appcode);//格式Authorization:APPCODE (中间是英文空格)
        int httpCode = httpURLConnection.getResponseCode();
        StringBuffer sb = new StringBuffer();
	    BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
	    String line = null;
	    while ((line = br.readLine()) != null) {
	        line = new String(line.getBytes(), "utf-8");
	        sb.append(line);
	    }
	    br.close();
        String json = sb.toString();
        System.out.println("/* 获取服务器响应状态码 200 正常；400 权限错误 ； 403 次数用完； */ ");
        System.out.println(httpCode);
        System.out.println("/* 获取返回的json   */ ");
        System.out.print(json);
        return json;
	}
}
